package com.tommy.test

import android.content.DialogInterface
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    private val appItemAdapter = AppItemAdapter()
    private val mainHandler = Handler(Looper.getMainLooper())
    private var workHandler: Handler? = null
    private var handlerThread: HandlerThread? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        handlerThread = HandlerThread("workHandler")
        handlerThread?.start()
        handlerThread?.looper?.let {
            workHandler = Handler(it)
        }
        rv_content.adapter = appItemAdapter
        appItemAdapter.itemClickListener = fun(_, appItemBean) {
            appItemBean.appPackageName?.let {
                val alertDialogBuilder = AlertDialog.Builder(this)
                alertDialogBuilder.setMessage("确定要打开应用：${appItemBean.appName}")
                alertDialogBuilder.setPositiveButton("确定") { _, _ ->
                    val intent = packageManager.getLaunchIntentForPackage(it)
                    startActivity(intent)
                }
                alertDialogBuilder.setNegativeButton("取消", null)
                alertDialogBuilder.show()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        loadApps()
    }

    private fun loadApps() {
        val packageManager = packageManager
        val packages: List<PackageInfo> = packageManager.getInstalledPackages(0)
        val appItems = arrayListOf<AppItemBean>()
        //遍历
        for (info in packages) {
            if (info.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
                val appItemBean = AppItemBean()
                //得到包名
                appItemBean.appPackageName = info.packageName
                //得到应用名称
                val ai: ApplicationInfo = packageManager.getApplicationInfo(info.packageName, 0)
                appItemBean.appName = ai.loadLabel(packageManager).toString()
                appItemBean.appVerName = info.versionName
                appItems.add(appItemBean)
            }
        }
        appItemAdapter.setNewItems(appItems)
    }

    override fun onDestroy() {
        super.onDestroy()
        mainHandler.removeCallbacksAndMessages(null)
        workHandler?.removeCallbacksAndMessages(null)
        handlerThread?.quit()
    }
}